﻿using B.S.DataBase.MyProject.Domain.SmartHealthcareZSJ;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.HospitalDepartCommand;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.HospitalDepartCommandCommand
{
    /// <summary>
    /// 医院科室查询命令处理类
    /// </summary>
    public class HospitalDepartQueryCommandHandler : IRequestHandler<HospitalDepartQueryCommand, ApiPaging<HospitalDepartmentZ>>
    {
        /// <summary>
        /// sugar
        /// </summary>
        private readonly SqlSugarContext sugar;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sugar"></param>
        public HospitalDepartQueryCommandHandler(SqlSugarContext sugar)
        {
            this.sugar = sugar;
        }
        /// <summary>
        /// 查询医院科室信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<HospitalDepartmentZ>> Handle(HospitalDepartQueryCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<HospitalDepartmentZ> result = new ApiPaging<HospitalDepartmentZ>();
            try
            {
                var list = sugar.db.Queryable<HospitalDepartmentZ>().Where(x => x.DeleteId == 0);

               
                if(request.LevelId!=null)
                {
                    list = list.Where(x => x.LevelId == request.LevelId);
                }
                if (request.DepartmentId != null)
                {
                    list = list.Where(x => x.ParentId == request.DepartmentId);
                }
                list = list.OrderByDescending(x => x.DepartmentId)
                           .Skip((request.PageIndex - 1) * request.PageSize)
                           .Take(request.PageSize);

                int TotalCount = list.Count();
                int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
                result.list = list.ToList();
                result.TotalCount = TotalCount;
                result.TotalPage = TotalPage;
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加团队信息时发生异常: {ex.Message}");
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
            }
            return await Task.FromResult(result);
        }
    }
}
